﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace DatabaseSynchronizer {
    public partial class CredentialForm : Form {

        private string _tfsURL = string.Empty;
        private bool _tfsURLRecieved = false;

        public CredentialForm(string[] args) {
            InitializeComponent();

            if (args.Length == 1) {
                _tfsURLRecieved = true;
                _tfsURL = args[0];
            }
        }

        private void CredentialForm_Load(object sender, EventArgs e) {

        }

        private void UsernameTextBox_Enter(object sender, EventArgs e) {

            if (UsernameTextBox.Text == @"Domain\User name") {
                UsernameTextBox.Text = string.Empty;
                UsernameTextBox.ForeColor = Color.Black;
            }
        }

        private void UsernameTextBox_Leave(object sender, EventArgs e) {

            if (UsernameTextBox.Text.Trim() == string.Empty) {
                UsernameTextBox.Text = @"Domain\User name";
                UsernameTextBox.ForeColor = Color.DimGray;
            }
        }

        public void CheckEnableOkButton(object sender, EventArgs e) {

            ErrorLabel.Text = string.Empty;

            if (UsernameTextBox.Text.Trim() != @"Domain\User name"
                && UsernameTextBox.Text.Trim() != string.Empty
                && PasswordTextBox.Text.Trim() != string.Empty) {

                OkButton.Enabled = true;
            }
            else {

                OkButton.Enabled = false;
            }

        }

        private NetworkCredential GetNetworkCredential() {

            //string[] id = UsernameTextBox.Text.Trim().Split('\\');
            return new NetworkCredential(UsernameTextBox.Text.Trim(), PasswordTextBox.Text);
        }

        private void OkButton_Click(object sender, EventArgs e) {

            if (_tfsURLRecieved) {
                string errMsg = string.Empty;
                ConnectionResult result = Utils.IsValidTfsUrl(_tfsURL, GetNetworkCredential(), out errMsg);

                if (result != ConnectionResult.Success) {
                    ErrorLabel.Text = errMsg;
                }
                else {
                    SelectServer.Username = UsernameTextBox.Text.Trim();
                    SelectServer.Password = PasswordTextBox.Text;
                    SelectServer.RememberCredentials = RememberCheckBox.Checked;
                    DialogResult = DialogResult.OK;
                    Close();
                }
            }
        }

        private void CancelButton_Click(object sender, EventArgs e) {
            DialogResult = DialogResult.Cancel;
            Close();
        }





    }
}
